from django.http import QueryDict
from django.template import Library
from django.urls import reverse
from django.conf import settings
from django.utils.safestring import mark_safe

register = Library()

def check_permission(request,name):
    role = request.user.role
    if name in settings.PERMISSION[role]:
        return True
    if name in settings.PERMISSION_PUBLIC:
        return True

@register.simple_tag
def add_permission(request,name,*args,**kwargs):
    if not check_permission(request,name):
        return ""
    url = reverse(name,args=args,kwargs=kwargs)
    rel = """<a href="{}" class="btn btn-success"><span class="glyphicon glyphicon-plus-sign"></span>新建</a>""".format(url)
    return mark_safe(rel)


@register.simple_tag
def edit_permission(request,name,*args,**kwargs):
    if not check_permission(request,name):
        return ""
    url = reverse(name,args=args,kwargs=kwargs)
    param = request.GET.urlencode()
    # print(param)
    if param:
        new_query_list = QueryDict(mutable=True)
        new_query_list['_filter'] = param
        filter_string = new_query_list.urlencode()
        # print(filter_string)
        rel = """<a href="{}?{}" class="btn btn-primary btn-xs">编辑</a>""".format(url, filter_string)
        # print(rel)
        return mark_safe(rel)
    rel = """<a href="{}" class="btn btn-primary btn-xs">编辑</a>""".format(url)
    return mark_safe(rel)
@register.simple_tag
def delete_permission(request,name,*args,**kwargs):
    if not check_permission(request,name):
        return ""
    cid = kwargs.get("pk")
    # url = reverse(name,args=args,kwargs=kwargs)
    rel ="""<a class="btn btn-danger btn-xs btn-lg btn_delete" cid="{}"  data-toggle="modal" data-target="#myModal">删除</a>""".format(cid)
    return mark_safe(rel)

@register.simple_tag
def delete_url_permission(request,name,*args,**kwargs):
    if not check_permission(request,name):
        return ""
    url = reverse(name,args=args,kwargs=kwargs)
    rel = """<a href="{}" class="btn btn-danger btn-xs">删除</a>""".format(url)
    return mark_safe(rel)

@register.filter
def has_permission(request,name):
    name_list = name.split(",")
    for name in name_list:
        if check_permission(request,name):
            return True
    return False


